package com.zbcz.crm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.VisitData
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date

class HomePageViewModel : ViewModel() {

    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)
    val mVisitDataLiveData = MutableLiveData<List<VisitData>>()

    companion object {
        // 获取当前系统时间戳
        fun formatCurrentDate(pattern: String = "yyyy-MM-dd"): String {
            val dateFormat = SimpleDateFormat(pattern)
            val currentDate = Date()
            return dateFormat.format(currentDate)
        }
    }


    fun getVisitList(visitorName: String) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                getVisitListSuspend(visitorName)?.let {
                    mVisitDataLiveData.postValue(it)
                }
            }
        }
    }

    private suspend fun getVisitListSuspend(visitorName: String): List<VisitData>? {
        try {
//            val result = mApi.getVisitList(
//                visitDate = formatCurrentDate(),
//                visitOrderStatus = "0",
//                visitorName = visitorName,
//                token = SharedPreferencesManager.getToken(CrmApplication.mApplication)
//            )
            val result = mApi.getVisitList(
                token = SharedPreferencesManager.getToken(CrmApplication.mApplication)
            )
            if (result.code == 200) {
                return result.result
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onCleared() {
        super.onCleared()
    }
}